package com.zhiyou100.api.date_demo;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

public class Demo4 {

    public static void main(String[] args) throws ParseException {

//        String saturday = getSaturday(new Date());
//        System.out.println("saturday = " + saturday);
        int days = getBetweenDays("2021-01-17", "2022-01-16");
        System.out.println("days = " + days);

    }

    //    获取指定日期所在周的周六日期
    public static String getSaturday(Date date){
        //利用日历类对象
        Calendar calendar = Calendar.getInstance();
        //保存指定时间
        calendar.setTime(date);
        //设置当前日期的周几为周六
        calendar.set(Calendar.DAY_OF_WEEK,Calendar.SATURDAY);
//        System.out.println("calendar = " + calendar);
        Date time = calendar.getTime();
        //将其转换为字符串类型的日期
        String s = new SimpleDateFormat("yyyy-MM-dd").format(time);
        return s;
    }


    //获取两个指定日期的相差天数   日期：2021-01-17
    /**
     * 根据注册游戏的时间获取用户的注册天数
     */
    public static int getBetweenDays(String str1,String str2) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = sdf.parse(str1);
        Date date2 = sdf.parse(str2);
        int day = 0;
        //计算间隔天数
        if (date.after(date2)){
            day = (int) ((date.getTime() - date2.getTime()) / (24 * 60 * 60 * 1000));
        }else {
            day = (int) ((date2.getTime() - date.getTime()) / (24 * 60 * 60 * 1000));
        }
        return day;
    }

}
